package com.chunxiadong.controller;

import com.chunxiadong.entity.*;
import com.chunxiadong.pojo.BlogInfo;
import com.chunxiadong.service.*;
import com.chunxiadong.utils.PasswordUtil;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.apache.log4j.Logger;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import javax.servlet.http.HttpSession;
import java.util.List;

/**
 * @auther QiuShangcheng
 * @create 2021/6/6
 */
@Controller
@RequestMapping("/user")
public class UserController {

    private final Logger log = Logger.getLogger(this.getClass());

    @Autowired
    FriendLinkService friendLinkService;

    @Autowired
    AdminService adminService;

    @Autowired
    PictureService pictureService;

    @Autowired
    BlogInfoService blogInfoService;

    @Autowired
    BlogService blogService;

    @Autowired
    CommentService commentService;

    @Autowired
    TypeService typeService;

    @Autowired
    MessageService messageService;

    //    搜索博客
    @PostMapping("/search")
    public String search(Model model,
                         @RequestParam(defaultValue = "1", value = "pageNum") Integer pageNum,
                         @RequestParam String query) {
        PageInfo<Blog> pageInfo = blogService.getSearchBlogByPage(pageNum, 100, new BlogBySearch(null, "%" + query + "%",true));
        model.addAttribute("pageInfo", pageInfo);
        model.addAttribute("query", query);
        return "search";
    }


    /**
     * 添加评论
     *
     * @param blogId
     * @param comment
     * @param model
     * @return
     */
    @RequestMapping("/addComment/{blogId}")
    public String addComment(@PathVariable Integer blogId, Comment comment, Model model) {
        if (comment.getContent().isEmpty() == false) {
            int i = commentService.addComment(comment);
        }
        Blog blog = blogService.getBlog(blogId);
        List<Comment> comments = commentService.getCommentListByBlogId(blogId);
        model.addAttribute("comments", comments);
        model.addAttribute("blog", blog);
        return "blog";
    }

    //    跳转博客详情页面
    @GetMapping("/blog/{id}")
    public String blog(@PathVariable Integer id, Model model,HttpSession session) {
        blogService.IncreaseViews(id);
        Blog blog = blogService.getBlog(id);
        List<Comment> comments = commentService.getCommentListByBlogId(id);
        BlogInfo blogInfo = blogInfoService.getBlogInfo();
        User blogger = adminService.getAdmin("chunxiadong");
        model.addAttribute("comments", comments);
        model.addAttribute("blog", blog);
        session.setAttribute("blogInfo",blogInfo);
        session.setAttribute("blogger",blogger);
        return "blog";
    }

    /**
     * 用于登录管理端
     *
     * @param admin
     * @param model
     * @return
     */
    @RequestMapping("/login")
    public String adminLogin(LoginAdmin admin, Model model, HttpSession session) {
        Subject subject = SecurityUtils.getSubject();
        UsernamePasswordToken token = new UsernamePasswordToken(admin.getNickname(),
                PasswordUtil.md5Hash(admin.getPassword(), admin.getNickname(), 1));
        try {
            subject.login(token);
            User user = adminService.getAdmin(admin.getNickname());
            log.info("curAdmin: " + user.toString());
            session.setAttribute("user", user);
            BlogInfo blogInfo = blogInfoService.getBlogInfo();
            session.setAttribute("blogInfo", blogInfo);
            return "admin/index";
        } catch (UnknownAccountException e) {
            model.addAttribute("msg", "UserName Error!");
            log.info(admin.toString() + "\nResult : {" + "UserName Error!" + "}");
            return "admin/login";
        } catch (IncorrectCredentialsException e) {
            model.addAttribute("msg", "PassWord Error!");
            log.info(admin.toString() + "\nResult : {" + "PassWord Error!" + "}");
            return "admin/login";
        }

    }

    /**
     * 控制未登陆的跳转
     *
     * @return
     */
    @RequestMapping("/toLogin")
    public String toLogin() {
        return "admin/login";
    }

    /**
     * //控制没授权的跳转
     *
     * @return
     */
    @RequestMapping("/unauthorized")
    public String unauthorized() {
        return "/error/403";
    }

    /**
     * 控制登录管理员端成功后的跳转
     *
     * @return
     */
    @RequestMapping("/loginSuccess")
    public String loginSuccess() {
        return "/admin/index";
    }

    /**
     * toAbout
     *
     * @return
     */
    @RequestMapping("/about")
    public String toAbout(HttpSession session) {
        BlogInfo blogInfo = blogInfoService.getBlogInfo();
        User blogger = adminService.getAdmin("chunxiadong");
        session.setAttribute("blogInfo",blogInfo);
        session.setAttribute("blogger",blogger);
        return "about";
    }

    /**
     * 博文分类
     * @param pageNum
     * @param id
     * @param model
     * @return
     */
    @RequestMapping("/type/{id}")
    public String toType(@RequestParam(defaultValue = "1", value = "pageNum") Integer pageNum, @PathVariable Integer id, Model model,HttpSession session) {
        List<Type> types = typeService.getAllType();
        //-1表示从首页导航点进来的
        if (id == -1) {
            id = types.get(0).getId();
        }
        BlogInfo blogInfo = blogInfoService.getBlogInfo();
        User blogger = adminService.getAdmin("chunxiadong");
        session.setAttribute("blogInfo",blogInfo);
        session.setAttribute("blogger",blogger);
        model.addAttribute("types", types);
        PageInfo<Blog> pageInfo = blogService.getSearchBlogByPage(pageNum, 5, new BlogBySearch(id, null,true));
        model.addAttribute("pageInfo", pageInfo);
        model.addAttribute("activeTypeId", id);
        return "type";
    }

    /**
     * 去往时间轴页面
     * @param model
     * @return
     */
    @RequestMapping("/archive")
    public String toArchive(Model model,HttpSession session){
        BlogInfo blogInfo = blogInfoService.getBlogInfo();
        User blogger = adminService.getAdmin("chunxiadong");
        session.setAttribute("blogInfo",blogInfo);
        session.setAttribute("blogger",blogger);
        List<Blog> blogs = blogService.getAllBlogToArchive();
        model.addAttribute("blogs",blogs);
        return "archive";
    }


    /**
     * 去往音乐盒
     * @return
     */
    @RequestMapping("/music")
    public String toMusic(HttpSession session){
        BlogInfo blogInfo = blogInfoService.getBlogInfo();
        User blogger = adminService.getAdmin("chunxiadong");
        session.setAttribute("blogInfo",blogInfo);
        session.setAttribute("blogger",blogger);
        return "music";
    }

    /**
     * 去往照片集
     * @param model
     * @return
     */
    @RequestMapping("/picture")
    public String toPicture(Model model,HttpSession session){
        BlogInfo blogInfo = blogInfoService.getBlogInfo();
        User blogger = adminService.getAdmin("chunxiadong");
        session.setAttribute("blogInfo",blogInfo);
        session.setAttribute("blogger",blogger);
        List<Picture> picture = pictureService.getAllPicture();
        model.addAttribute("pictures",picture);
        return "picture";

    }

    /**
     * 去友人帐页面
     * @param model
     * @return
     */
    @RequestMapping("/friend")
    public String toFriend(Model model,HttpSession session){
        BlogInfo blogInfo = blogInfoService.getBlogInfo();
        User blogger = adminService.getAdmin("chunxiadong");
        session.setAttribute("blogInfo",blogInfo);
        session.setAttribute("blogger",blogger);
        List<FriendLink> allFriendLink = friendLinkService.getAllFriendLink();
        model.addAttribute("friendlinks",allFriendLink);
        return "friend";
    }

    /**
     * 去留言板页面
     * @param model
     * @return
     */
    @RequestMapping("/message")
    public String toMessage(Model model,HttpSession session){
        BlogInfo blogInfo = blogInfoService.getBlogInfo();
        User blogger = adminService.getAdmin("chunxiadong");
        session.setAttribute("blogInfo",blogInfo);
        session.setAttribute("blogger",blogger);
        List<Message> allMessage = messageService.getAllMessage();
        model.addAttribute("messages",allMessage);
        return "message";
    }

    /**
     * 添加留言
     * @param message
     * @param attributes
     * @return
     */
    @RequestMapping("/addMessage")
    public String addMessage(Message message, RedirectAttributes attributes){
        messageService.addMessage(message);
        return "redirect:message";
    }
}
